{% extends "base.html" %}

{% block title %}仪表盘 - 会议管理系统{% endblock %}

{% block content %}
<div class="alert-container mb-4"></div>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-speedometer2 me-2"></i>仪表盘</h2>
    </div>
    <div class="col-md-6 text-md-end">
        <a href="/meetings/create" class="btn btn-primary">
            <i class="bi bi-plus-circle me-1"></i>预约会议
        </a>
    </div>
</div>

<div class="row">
    <!-- 统计卡片 -->
    <div class="col-md-4 mb-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-4">
                <div class="display-3 text-primary mb-3">
                    <i class="bi bi-calendar-check"></i>
                </div>
                <h3 class="card-title fw-bold" id="upcomingMeetingCount">0</h3>
                <p class="text-muted">即将召开的会议</p>
                <a href="/my-meetings" class="btn btn-sm btn-outline-primary mt-2">查看我的会议</a>
            </div>
        </div>
    </div>

    <div class="col-md-4 mb-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-4">
                <div class="display-3 text-success mb-3">
                    <i class="bi bi-building"></i>
                </div>
                <h3 class="card-title fw-bold" id="availableRoomCount">0</h3>
                <p class="text-muted">可用会议室</p>
                <a href="/rooms" class="btn btn-sm btn-outline-success mt-2">查看所有会议室</a>
            </div>
        </div>
    </div>

    <div class="col-md-4 mb-4">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body text-center p-4">
                <div class="display-3 text-warning mb-3">
                    <i class="bi bi-people"></i>
                </div>
                <h3 class="card-title fw-bold" id="participatingMeetingCount">0</h3>
                <p class="text-muted">参与的会议</p>
                <a href="/meetings" class="btn btn-sm btn-outline-warning mt-2">查看所有会议</a>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-8">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                    <i class="bi bi-calendar-week me-2"></i>近期会议
                </h5>
                <div>
                    <a href="/my-meetings" class="btn btn-sm btn-outline-primary">查看更多</a>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>会议</th>
                                <th>时间</th>
                                <th>会议室</th>
                                <th>状态</th>
                            </tr>
                        </thead>
                        <tbody id="upcomingMeetingsList">
                            <tr>
                                <td colspan="4" class="text-center py-4 text-muted">
                                    <i class="bi bi-info-circle me-2"></i>正在加载会议数据...
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="card-title mb-0">
                    <button class="btn btn-link text-decoration-none p-0 text-dark d-flex justify-content-between align-items-center w-100" 
                            type="button" 
                            data-bs-toggle="collapse" 
                            data-bs-target="#roomStatusCollapse" 
                            aria-expanded="true" 
                            aria-controls="roomStatusCollapse">
                        <span><i class="bi bi-building me-2"></i>会议室可用状态</span>
                        <i class="bi bi-chevron-down"></i>
                    </button>
                </h5>
            </div>
            <div class="collapse show" id="roomStatusCollapse">
                <div class="card-body">
                    <div id="roomStatusList">
                        <div class="d-flex justify-content-center py-4">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">正在加载...</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h5 class="card-title mb-0">
                    <i class="bi bi-calendar3 me-2"></i>今日日期
                </h5>
            </div>
            <div class="card-body text-center">
                <div class="display-4 fw-bold text-primary" id="currentDate"></div>
                <p class="text-muted" id="currentDay"></p>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extrajs %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 加载日期信息
        const now = new Date();
        const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        const months = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'];
        
        document.getElementById('currentDate').innerText = `${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()}`;
        document.getElementById('currentDay').innerText = days[now.getDay()];
        
        // 设置token
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
            console.log('认证已设置');
            
            // 加载数据
            getUpcomingMeetings();
            getRoomStatus();
            getStatistics();
        } else {
            console.error('未找到token，请先登录');
            document.querySelector('.alert-container').innerHTML = `
                <div class="alert alert-warning alert-dismissible fade show" role="alert">
                    <strong>未登录!</strong> 您需要先登录才能查看完整的仪表盘信息。
                    <a href="/login" class="btn btn-sm btn-primary ms-3">去登录</a>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            `;
        }
    });
    
    function getUpcomingMeetings() {
        axios.get('/api/meetings/my-meetings', {
            params: {
                start_date: new Date().toISOString()
            }
        })
        .then(response => {
            const meetings = response.data;
            const meetingsList = document.getElementById('upcomingMeetingsList');
            
            if (meetings.length === 0) {
                meetingsList.innerHTML = `
                    <tr>
                        <td colspan="4" class="text-center py-4 text-muted">
                            <i class="bi bi-calendar-x me-2"></i>没有即将召开的会议
                        </td>
                    </tr>
                `;
                return;
            }
            
            // 按开始时间排序
            meetings.sort((a, b) => new Date(a.start_time) - new Date(b.start_time));
            
            // 只显示前5个会议
            const upcomingMeetings = meetings.slice(0, 5);
            
            meetingsList.innerHTML = upcomingMeetings.map(meeting => {
                const startTime = new Date(meeting.start_time);
                const endTime = new Date(meeting.end_time);
                const timeStr = `${formatDateTime(startTime)} - ${formatTime(endTime)}`;
                
                let statusBadge = '';
                if (meeting.is_cancelled) {
                    statusBadge = '<span class="badge bg-danger">已取消</span>';
                } else if (startTime <= new Date() && endTime >= new Date()) {
                    statusBadge = '<span class="badge bg-success">进行中</span>';
                } else if (startTime > new Date()) {
                    statusBadge = '<span class="badge bg-primary">待开始</span>';
                } else {
                    statusBadge = '<span class="badge bg-secondary">已结束</span>';
                }
                
                return `
                    <tr>
                        <td>
                            <a href="/meetings/${meeting.id}" class="text-decoration-none fw-bold">${meeting.title}</a>
                        </td>
                        <td>${timeStr}</td>
                        <td>${meeting.room_name || meeting.room.name}</td>
                        <td>${statusBadge}</td>
                    </tr>
                `;
            }).join('');
        })
        .catch(error => {
            console.error('获取会议失败:', error);
            const meetingsList = document.getElementById('upcomingMeetingsList');
            meetingsList.innerHTML = `
                <tr>
                    <td colspan="4" class="text-center py-4 text-danger">
                        <i class="bi bi-exclamation-triangle me-2"></i>获取会议数据失败
                    </td>
                </tr>
            `;
        });
    }
    
    function getRoomStatus() {
        // 确保请求头中包含token
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        }
        
        axios.get('/api/rooms/')
        .then(response => {
            const rooms = response.data.rooms || [];
            const roomStatusList = document.getElementById('roomStatusList');
            
            if (rooms.length === 0) {
                roomStatusList.innerHTML = '<p class="text-center text-muted py-3">没有可用的会议室</p>';
                return;
            }
            
            // 检查每个会议室当前是否有会议
            const promises = rooms.map(room => {
                // 确保每个请求都带有正确的授权头
                // 使用完整的ISO日期格式
                const today = new Date();
                const formattedDate = today.toISOString();
                
                return axios.get('/api/meetings/', {
                    params: {
                        room_id: room.id,
                        start_date: formattedDate
                    },
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                })
                .then(res => {
                    const currentMeetings = res.data.filter(meeting => {
                        const startTime = new Date(meeting.start_time);
                        const endTime = new Date(meeting.end_time);
                        const now = new Date();
                        return !meeting.is_cancelled && startTime <= now && endTime >= now;
                    });
                    
                    return {
                        ...room,
                        isOccupied: currentMeetings.length > 0,
                        currentMeeting: currentMeetings[0]
                    };
                })
                .catch((error) => {
                    console.error(`获取会议室${room.name}的会议状态失败:`, error);
                    return {
                        ...room,
                        isOccupied: false,
                        currentMeeting: null,
                        error: true
                    };
                });
            });
            
            Promise.all(promises)
                .then(roomsWithStatus => {
                    roomStatusList.innerHTML = roomsWithStatus.map((room, index) => {
                        const statusBadge = room.isOccupied 
                            ? '<span class="badge bg-danger">占用中</span>' 
                            : '<span class="badge bg-success">空闲</span>';
                        
                        const meetingInfo = room.isOccupied && room.currentMeeting
                            ? `<small class="d-block text-muted mt-1">当前会议: ${room.currentMeeting.title}</small>`
                            : '';
                        
                        // 每个会议室项目都是可折叠的
                        return `
                            <div class="mb-2">
                                <div class="d-flex justify-content-between align-items-start p-2 border-bottom" 
                                     style="cursor: pointer;"
                                     data-bs-toggle="collapse" 
                                     data-bs-target="#roomDetail${index}" 
                                     aria-expanded="${index < 3 ? 'true' : 'false'}" 
                                     aria-controls="roomDetail${index}">
                                    <div class="d-flex align-items-center">
                                        <h6 class="mb-0 me-2">${room.name}</h6>
                                        ${statusBadge}
                                    </div>
                                    <i class="bi bi-chevron-down fs-6"></i>
                                </div>
                                <div class="collapse ${index < 3 ? 'show' : ''}" id="roomDetail${index}">
                                    <div class="px-2 py-1">
                                        <div class="small text-muted">容纳 ${room.capacity} 人 · ${room.location}</div>
                                        ${meetingInfo}
                                        <div class="mt-2">
                                            <a href="/rooms/${room.id}" class="btn btn-sm btn-outline-info">查看详情</a>
                                            <a href="/meetings/create?room=${room.id}&attendees=1" class="btn btn-sm btn-outline-primary">
                                                <i class="bi bi-calendar-plus"></i> 预约
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('');
                    
                    // 添加折叠/展开全部按钮
                    roomStatusList.innerHTML += `
                        <div class="d-flex justify-content-between mt-3">
                            <button class="btn btn-sm btn-outline-secondary" id="expandAllRooms">展开全部</button>
                            <button class="btn btn-sm btn-outline-secondary" id="collapseAllRooms">折叠全部</button>
                        </div>
                    `;
                    
                    // 添加展开/折叠全部的事件监听
                    document.getElementById('expandAllRooms').addEventListener('click', () => {
                        roomsWithStatus.forEach((_, index) => {
                            const collapse = new bootstrap.Collapse(document.getElementById(`roomDetail${index}`), {
                                toggle: false
                            });
                            collapse.show();
                        });
                    });
                    
                    document.getElementById('collapseAllRooms').addEventListener('click', () => {
                        roomsWithStatus.forEach((_, index) => {
                            const collapse = new bootstrap.Collapse(document.getElementById(`roomDetail${index}`), {
                                toggle: false
                            });
                            collapse.hide();
                        });
                    });
                });
        })
        .catch(error => {
            console.error('获取会议室失败:', error);
            const roomStatusList = document.getElementById('roomStatusList');
            roomStatusList.innerHTML = '<p class="text-center text-danger py-3">获取会议室数据失败</p>';
        });
    }
    
    function getStatistics() {
        // 确保请求头中包含token
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        }
        
        axios.get('/api/meetings/my-meetings', {
            params: {
                start_date: new Date().toISOString()
            },
            headers: {
                'Authorization': 'Bearer ' + token
            }
        })
        .then(response => {
            const upcomingMeetings = response.data.filter(meeting => !meeting.is_cancelled && new Date(meeting.start_time) > new Date());
            document.getElementById('upcomingMeetingCount').innerText = upcomingMeetings.length;
            
            const participatingMeetings = response.data.filter(meeting => 
                !meeting.is_cancelled && 
                new Date(meeting.end_time) > new Date() && 
                meeting.owner_id !== localStorage.getItem('user_id')
            );
            document.getElementById('participatingMeetingCount').innerText = participatingMeetings.length;
        })
        .catch(error => {
            console.error('获取会议统计数据失败:', error);
        });
        
        axios.get('/api/rooms/', {
            headers: {
                'Authorization': 'Bearer ' + token
            }
        })
        .then(response => {
            document.getElementById('availableRoomCount').innerText = response.data.rooms.length;
        })
        .catch(error => {
            console.error('获取会议室统计数据失败:', error);
        });
    }
    
    function formatDateTime(date) {
        return `${date.getMonth() + 1}月${date.getDate()}日 ${formatTime(date)}`;
    }
    
    function formatTime(date) {
        return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
</script>
{% endblock %} 